<template>
	<div style="padding: 10px 36px;">
		<el-transfer class="trans" v-model="value" 
				:data="data" :titles="['待添加人员', '已添加组人员']"/>
	</div>
</template>

<script>
import API from '@/api/index.js'
import Token from '@/api/token.js'

export default {
	props: {
		//拿到父组件的组id
		id: Number
	},
	data(){
		return {
			value: [] , // 已选中的人员ID
			data: [],  // 所有人员列表
			getuser: Token.getUser(),
			assignedUserIds: [] // 初始已分配的用户ID
		}
	},
	created() {
		this.getstudent();
		this.getAssignedGroup();
	},
	
	methods: {
		getstudent(){
			const params = {
				clazz_id: this.getuser.clazz_id,
				name: this.getuser.name
			};
			API.getGroupList(params).then(response => {
				this.data = response.data.map(item => ({
					key: item.id,
					label: item.name
				}))
			});
		},
		getAssignedGroup() {
			// API.getAssignedUsers返回已分组用户id数组
			console.log(this.id)
			API.getAssignedGroup({
				group_id: this.id,  
			}).then(res => {
				const ids = res.data.map(item => item.id); // 提取id数组
				this.value = ids;
				console.log(this.value)
				this.assignedUserIds = [...ids];
			});
		},
		handleSave() {
			const toAdd = this.value.filter(id => !this.assignedUserIds.includes(id));
			const toRemove = this.assignedUserIds.filter(id => !this.value.includes(id));
			if (toAdd.length > 0) {
				console.log("分配组员")
				API.assignGroupUser({ userIds: toAdd, group_id: this.id });
			}
			if (toRemove.length > 0) {
				console.log("删除组员")
				API.deleteGroupUser({ userIds: toRemove, group_id: this.id });
			}
			this.assignedUserIds = [...this.value]; // 更新本地记录
			this.$message.success('保存成功！');
		},
		reset() {
			this.value = [...this.assignedUserIds];
		},
	},
	watch: {
		// 监听id变化后 就执行一次查询
		id(newId) {
			this.getAssignedGroup();
		}
	},
}
</script>

<style>
.trans .el-transfer__buttons {
	text-align: center;
}

.trans .el-transfer__button {
	display: block !important;
	margin: 8px 0 !important;
}

.trans .el-transfer-panel__body, .trans .el-transfer-panel__list {
	height: 600px !important;
}

</style>